"use strict";

/**
 * @apiDefine Login 登录
 * @apiHeader {String} Authorization 登录验证
 * @apiHeaderExample {json} Header-Example:
 * {
 *     "Authorization": "login-token",
 * }
 */
module.exports = () => {
    /**
     *
     * @param {Egg.Context} ctx
     * @param {Function} next
     *
     */
    async function handelr(ctx, next) {
        const token = ctx.request.header.authorization || "";
        const site_author = 1;// ctx.locals.siteSetting.site_author;
        const auth = { uid: 0, isLogin: false };


        try {


            // 测试token
            if (ctx.app.config.env === "local") {

                if (token === "login-token") {
                    auth.uid = 2; // 测试用户ID
                    auth.isLogin = true;
                    return;
                }

                if (token === "login-token-admin") {
                    auth.uid = site_author;
                    auth.isLogin = true;
                    return;
                }

            }


            // 调用解析登录jwt服务
            const { sub: uid } = await ctx.service.jsonWebToken.verifyLoginToken(token.replace("Bearer ", ""));


            auth.uid = uid;
            auth.isLogin = true;


        } catch (error) {
            /**
             * JsonWebTokenError
             * Error object:
             *
             * name: 'JsonWebTokenError'
             * message:
             * 'jwt malformed'
             * 'jwt signature is required'
             * 'invalid signature'
             * 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
             * 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
             * 'jwt id invalid. expected: [OPTIONS JWT ID]'
             * 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
             *
             *  https://www.npmjs.com/package/jsonwebtoken
             */
            const JsonWebTokenError = [
                "jwt malformed",
                "jwt signature is required",
                "invalid signature",
                "jwt audience invalid",
                "jwt issuer invalid",
                "jwt id invalid",
                "jwt subject invalid",
            ];


            if (JsonWebTokenError.includes(error.message)) {
                // 这里记录下jwt解析错误的信息
            } else if (error.message === "jwt must be provided") {
                // 可以不带token
            } else if (ctx.app.config.env === "local") {
                // eslint-disable-next-line no-console
                console.error(error);
            }


        } finally {
            Object.defineProperty(ctx.locals, "auth", {
                get() {
                    return {
                        get uid() {
                            return Number(auth.uid);
                        },
                        isLogin() {
                            if (auth.isLogin === false) {
                                // ctx.returnBody(-401, "未登录");
                                ctx.throw(401, "未登录", { user: "user" });
                            }
                            return auth.isLogin;
                        },
                    };
                },
                set() { /** 禁止在此中间件外修改登录状态 */ },
            });
            await next();
        }


    }


    return handelr;


};
